package com.lhd.charging.order.mqtt;

import com.lhd.charging.order.common.JsonUtils;
import com.lhd.charging.order.constant.Constant;
import com.lhd.charging.order.dao.repository.OrderRepository;
import com.lhd.charging.order.pojo.param.DeviceResultParam;
import com.lhd.charging.order.pojo.po.ChargingBillFailPO;
import com.lhd.charging.order.pojo.po.ChargingBillSuccessPO;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

@Slf4j
public class MqttConsumer implements MqttCallbackExtended {

    private MqttClient mqttClient;
    private OrderRepository orderRepository;
    public MqttConsumer(MqttClient mqttClient, OrderRepository orderRepository) {
        this.mqttClient = mqttClient;
        this.orderRepository = orderRepository;
    }

    @Override
    public void connectComplete(boolean b, String s) {
        log.debug("MqttConsumer:连接成功");

        try {
            mqttClient.subscribe("/topic/start/result",0);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void connectionLost(Throwable throwable) {
        log.debug("MqttConsumer:连接丢失");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.debug("MqttConsumer:接收到消息-{},message-{}",topic,message);

        DeviceResultParam deviceResultParam = JsonUtils.toObject(message.toString(), DeviceResultParam.class);
        if (deviceResultParam != null){
            String result = deviceResultParam.getResult();
            if (Constant.RESULT_START_CHARGING_SUCCESS.equals(result)){
                log.debug("充电桩开始充电");
                //创建订单成功记录
                deviceResultParam.getOrderNo();
                //orderService.saveSuccessOrder(deviceResultParam);
                ChargingBillSuccessPO chargingBillSuccessPO = new ChargingBillSuccessPO();
                chargingBillSuccessPO.setBillId(deviceResultParam.getOrderNo());
                orderRepository.saveSuccessOrder(chargingBillSuccessPO);
            }else {
                log.debug("充电桩故障");
                //创建订单失败记录
                ChargingBillFailPO chargingBillFailPO = new ChargingBillFailPO();
                chargingBillFailPO.setBillId(deviceResultParam.getOrderNo());
                chargingBillFailPO.setFailDesc("设备自检失败");
                orderRepository.saveFailOrder(chargingBillFailPO);
            }
        }

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.debug("MqttConsumer:消息处理完成");
    }
}
